package com.example.wechatdaka.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.wechatdaka.entity.User;
import com.example.wechatdaka.entity.UserWechat;
import com.example.wechatdaka.service.UserService;
import com.example.wechatdaka.service.UserWechatService;
import com.example.wechatdaka.utils.Result;
import com.example.wechatdaka.utils.SendCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lx
 * @since 2020-11-29
 */
@Api(tags = "微信后台模块")
@RestController
@RequestMapping("/userwechat")
public class UserWechatController {
    @Autowired
    private UserWechatService userWechatService;
    @Autowired
    private UserService userService;

    @ApiOperation(value = "微信加载登录")
    @RequestMapping(value = "/wechatLogin",method = RequestMethod.GET)
    public Result wechatLogin(@RequestParam String code){
        System.out.println("wechatLogin code"+code);
        SendCode sendCode=new SendCode();
        String openId = sendCode.getOpenId(code);
        UserWechat userWechat = userWechatService.selectByOpenId(openId);
        if (userWechat!=null){
            return new Result(Result.SUCCESS,userWechat,"SUCCESS");
        }
        return new Result(Result.ERROR,openId,"error");
    }
    @ApiOperation(value = "微信绑定学号")
    @RequestMapping(value = "/saveStudent",method = RequestMethod.POST)
    public Result saveStudent(@RequestBody UserWechat userWechat){
        System.out.println(userWechat.toString());
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("lxUserNumber",userWechat.getLxUserNumber());
        User user = userService.getOne(userQueryWrapper);   //乱输账号会空指针
        if (user!=null){
            QueryWrapper<UserWechat> userWechatQueryWrapper=new QueryWrapper<>();
            userWechatQueryWrapper.eq("lxUserId",user.getId());
            UserWechat one = userWechatService.getOne(userWechatQueryWrapper);
            if (one!=null){ //判断是否多微信绑定一个账号
                return new Result(Result.ERROR,null,"该学号已被绑定");
            }
            userWechat.setLxUserId(user.getId());
            boolean save = userWechatService.save(userWechat);
            if (save){
                return new Result(Result.SUCCESS,null,"SUCCESS");
            }

        }
        return new Result(Result.ERROR,null,"不存在该学号");
    }



}

